<template>
    <div class="control list_container flex both-100">
        <Breadcrumb :title="pageTitle" />
        <div class="content_container">
            <el-form ref="searchForm" :inline="true" :model="searchMap" class="search_wrapper flex-space-between">
                <div class="search">
                    <el-form-item prop="dangerousSourceName" size="small">
                        <el-input v-model="searchMap.dangerousSourceName" placeholder="请输入危险源名称"></el-input>
                    </el-form-item>
                    <el-form-item prop="dangerousSourceName" size="small" class="flex">
                        <el-button @click="handleSearch()" class="btn_primary el-icon-search">查询</el-button>
                        <el-button @click="handleReset()" class="btn_cancel el-icon-refresh-left">重置</el-button>
                    </el-form-item>
                </div>
                <div class="edit">
                    <el-form-item class="flex">
                        <el-button @click="handleAdd()" class="btn_primary el-icon-plus">新增</el-button>
                    </el-form-item>
                </div>
            </el-form>
            <div class="table_container">
                <!-- 表格 -->
                <el-table :data="dataList" v-loading="loading" stripe class="per_table" style="width: 100%"
                    :height="winTableH">
                    <el-table-column prop="deptName" label="所属单位"></el-table-column>
                    <el-table-column prop="dangerousSourceName" label="危险源名称" align="center"></el-table-column>
                    <el-table-column prop="dangerousSourceCode" label="危险源编码" align="center"></el-table-column>
                    <el-table-column prop="dangerousSourceType" label="危险源类型" align="center">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.dangerous_source_type" :value="scope.row.dangerousSourceType" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="dangerousSourceLevel" label="危险源等级" align="center">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.dangerous_source_level" :value="scope.row.dangerousSourceLevel" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="detailedAddress" label="地址" align="center"></el-table-column>
                    <el-table-column label="操作" width="280">
                        <template slot-scope="scope">
                            <div>
                                <span type="text" class="tag_primary" size="small"
                                    @click="handleSelect(scope.row)">查看</span>
                                <span type="text" class="marginl-10 tag_primary" size="small"
                                    @click="handleEdit(scope.row)">编辑</span>
                                <span type="text" class="marginl-10 tag_warning" size="small"
                                    @click="handleDelete(scope.row)">删除</span>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <Pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize"
                @change="getList"></Pagination>
        </div>
        <!-- 弹窗 新增 -->
        <el-dialog class="m_dialog" :title="title" :visible.sync="dialogVisible" width="800" append-to-body
            :before-close="() => { dialogVisible = false }" :close-on-click-modal="false">
            <div class="content">
                <el-form ref="form" :key="reqType" :model="formModel" size="small" :rules="formRules" label-width="80px">
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <el-form-item label="所属单位" label-width="120px" prop="deptId">
                                <treeselect v-model="formModel.deptId" :options="deptOptions" :show-count="true"
                                    placeholder="请选择所属单位" @input="projectInput" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="危险源名称" label-width="120px" prop="dangerousSourceName">
                                <el-input v-model="formModel.dangerousSourceName" placeholder="请输入危险源名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="危险源编码" label-width="120px" prop="dangerousSourceCode">
                                <el-input v-model="formModel.dangerousSourceCode" placeholder="请输入危险源编码"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="危险源类型" label-width="120px" prop="dangerousSourceType">
                                <el-select v-model="formModel.dangerousSourceType" placeholder="请选择危险源类型"
                                    style="width: 100%;">
                                    <el-option v-for="(item, index) in dict.type.dangerous_source_type" :label="item.label"
                                        :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="危险源等级" label-width="120px" prop="dangerousSourceLevel">
                                <el-select v-model="formModel.dangerousSourceLevel" placeholder="请选择危险源等级"
                                    style="width: 100%;">
                                    <el-option v-for="(item, index) in dict.type.dangerous_source_level" :label="item.label"
                                        :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="位置" label-width="120px" prop="location">
                                <el-select v-model="formModel.location" placeholder="请选择平面图" @change="selectChange">
                                    <el-option v-for="item in picList" :key="item.projectPointPicId" :label="item.picName"
                                        :value="item.projectPointPicId">
                                    </el-option>
                                </el-select>
                                <el-button :disabled="false" @click="imageAnnotation()" type="primary">标注</el-button>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="详细地址" label-width="120px" prop="detailedAddress">
                                <el-input v-model="formModel.detailedAddress" placeholder="请输入详细地址"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="负责人" label-width="120px" prop="commanderUserId">
                                <el-select v-model="formModel.commanderUserId" placeholder="请选择负责人" style="width: 100%;">
                                    <el-option v-for="item in userOptions" :key="item.userId" :label="item.nickName"
                                        :value="item.userId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系电话" label-width="120px" prop="phonenumber">
                                <el-input v-model="formModel.phonenumber" placeholder="请输入联系电话"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="备注" label-width="120px">
                                <el-input v-model="formModel.remark" type="textarea" placeholder="请输入备注"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="() => { dialogVisible = false }" class="btn_cancel">取 消</el-button>
                <el-button type="primary" @click="submitFrom()" class="btn_primary">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog class="m_dialog" :title="title" :visible.sync="dialogVisibleInfo" width="800" append-to-body>
            <custom-title title="详细信息" />
            <BaseDescriptions :descConfig="descConfig" :descConfigItem="descConfigItem" :descModel="formModel">
                <template #dangerousSourceType>
                    <dict-tag :options="dict.type.dangerous_source_type" :value="formModel.dangerousSourceType" />
                </template>
                <template #dangerousSourceLevel>
                    <dict-tag :options="dict.type.dangerous_source_level" :value="formModel.dangerousSourceLevel" />
                </template>
                <template #location>
                        <el-button @click="imageAnnotation('slot')" type="small">标注</el-button>
                    </template>
            </BaseDescriptions>
        </el-dialog>
        <!-- 地图弹窗 -->
        <el-dialog class="m_dialog" title="请选择经纬度" :visible.sync="isVisibleMap" width="800" append-to-body
            :before-close="() => { isVisibleMap = false }" :close-on-click-modal="false">
            <div class="content" style="position: relative">
                <div class="mapDiv" ref="map" :key="mapKey" style="width: 100%; height: 466px"></div>
                <div class="map-Contern">
                    <el-form class="map-form" size="small" ref="mapForm" :model="mapForm" label-width="0">
                        <!-- <el-form-item label="">
                            <el-input v-model="mapForm.mapSearch" placeholder="搜索地区">
                                <template slot="suffix">
                                    <i class="el-icon-search" @click="mapSearchFn"></i>
                                </template>
                            </el-input>
                        </el-form-item> -->
                        <el-form-item label="">
                            <span style="color: #8fabbf">经纬度</span>
                            <el-input v-model="mapForm.maplnglat" placeholder=""> </el-input>
                        </el-form-item>
                        <!-- <el-form-item label="">
                            <span style="color: #8fabbf">地址</span>
                            <el-input v-model="mapForm.mapaddress" placeholder="请选择地址"></el-input>
                        </el-form-item> -->
                    </el-form>
                    <div slot="footer" class="map-footer-btn">
                        <el-button @click="() => { isVisibleMap = false }" class="btn_cancel">取 消</el-button>
                        <el-button type="primary" @click="mapSubmitForm" class="btn_primary">确 定</el-button>
                    </div>
                </div>
            </div>
        </el-dialog>

        <el-dialog class="m_dialog" title="标注" :visible.sync="markDialogVisible" width="800" append-to-body
            :close-on-click-modal="false">
            <PlanPosition2 :formData="positionData" :key="planPositionKey" :pictrue="pictrue" @setPosition="getPosition"></PlanPosition2>
        </el-dialog>

    </div>
</template>
<script>
import request from "@/utils/request";
import { dangerousSource, dangerousSourceList, riskControlMeasuresInfo } from '../api/index'
import { getProjectPointPicList } from '@/api/projectPoints/projectImg.js'
import BaseDescriptions from '@/components/PageContent/BaseDescriptions.vue';
import PlanPosition2 from '../../system/project/riskPoint/PlanPosition2.vue'
import { listUser, deptTreeSelect, userDeptTreeSelect } from '@/api'

import Map from "ol/Map";
import View from "ol/View";
import XYZ from "ol/source/XYZ";
import Feature from "ol/Feature.js";
import Point from "ol/geom/Point.js";
import { Circle, Fill, Icon, Stroke, Style, Text } from "ol/style.js";
import { OGCMapTile, Vector as VectorSource } from "ol/source.js";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer.js";

export default {
    dicts: ['dangerous_source_level', 'dangerous_source_type'],
    data() {
        return {
            picList: [],
            dialogVisibleInfo: false,
            markDialogVisible: false,
            planPositionKey:0,
            positionData: {
                positionX: 0,
                positionY: 0,
            },
            pictrue: {},
            pageTitle: '危险源',
            loading: true,
            total: 0,
            title: '危险源详情',
            dialogVisible: false,
            deptOptions: undefined,
            userOptions: [],
            reqType: 'post',
            descConfig: {
                size: 'medium',
                column: '2',
            },
            // 地图表单
            mapForm: {
                mapSearch: undefined,
                maplnglat: undefined,
                mapaddress: undefined,
            },
            // 是否可见地图
            isVisibleMap: false,
            // 地图
            map: null,
            // 天地图token
            mapToken: "f01023d9e7977aa8946e0137daf05a2b",
            // 地图矢量图层源
            vectorSource: undefined,
            // 地图点位图片样式
            iconStyle: undefined,
            searchMap: {
                pageNum: 1,
                pageSize: 10,
            },
            dataList: [],
            // 提交表单数据
            formModel: {},
            mapKey: 0,
            formRules: {
                deptId: {
                    required: true,
                    message: "所属单位不能为空",
                    trigger: "change",
                },
                dangerousSourceName: {
                    required: true,
                    message: "危险源名称不能为空",
                    trigger: "change",
                },
                dangerousSourceCode: {
                    required: true,
                    message: "危险源编码不能为空",
                    trigger: "change",
                },
                dangerousSourceType: {
                    required: true,
                    message: "危险源类型不能为空",
                    trigger: "change",
                },
                dangerousSourceLevel: {
                    required: true,
                    message: "危险源等级不能为空",
                    trigger: "change",
                },
                location: {
                    required: true,
                    message: "位置不能为空",
                    trigger: "change",
                },
                detailedAddress: {
                    required: true,
                    message: "详细地址不能为空",
                    trigger: "change",
                },
            },
            descConfigItem: [
                {
                    fieIdName: 'deptName',
                    label: '所属单位',
                    span: 2,
                },
                {
                    fieIdName: 'dangerousSourceName',
                    label: '危险源名称',
                    span: 2,
                }, {
                    fieIdName: 'dangerousSourceCode',
                    label: '危险源编码',
                    span: 2,
                }, {
                    fieIdName: 'dangerousSourceType',
                    label: '危险源类型',
                    span: 2,
                    slotName: 'dangerousSourceType',
                }, {
                    fieIdName: 'dangerousSourceLevel',
                    label: '危险源等级',
                    span: 2,
                    slotName: 'dangerousSourceLevel',
                },  {
                    fieIdName: 'detailedAddress',
                    label: '详细地址',
                    span: 2,
                }, 
                {
                    fieIdName: 'commanderUserName',
                    label: '负责人',
                    span: 2,
                }, {
                    fieIdName: 'phonenumber',
                    label: '联系电话',
                    span: 12,
                }, {
                    fieIdName: 'remark',
                    label: '备注',
                    span: 12,
                },{
                    fieIdName: 'location',
                    label: '位置',
                    span: 12,
                    slotName: 'location',
                },
            ],
        }
    },
    components: {
        BaseDescriptions, PlanPosition2
    },
    methods: {
        submitFrom() {
            console.log(this.formModel, '入参')
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let params = {
                        ...this.formModel,
                        positions: [
                            { x: this.tempPosition.positionX | 0, y: this.tempPosition.positionY | 0}
                        ] ,
                    }
                    dangerousSource(params,this.reqType).then(res => {
                        if (200 === res.code) {
                            this.$message({
                                message: '操作成功',
                                type: 'success',
                            });
                            this.dialogVisible = false
                            this.getList()
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        //删除
        handleDelete(row) {
            this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                dangerousSource([row.dangerousSourceId], 'delete').then(res => {
                    if (200 === res.code) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getList()
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 查询
        handleSearch() {
            this.getList()
        },
        // 重置
        handleReset() {
            this.searchMap = {
                pageNum: 1,
                pageSize: 10,
            }
            this.getList()
        },
        //新增打开
        handleAdd() {
            this.title = "新增危险源"
            this.reqType = 'post'
            if (this.$refs.form) {
                this.$refs.form.resetFields()
            }
            this.formModel = {}
            this.dialogVisible = true;
        },
        //编辑
        handleEdit(row) {
            this.title = "编辑危险源"
            this.reqType = 'put'
            this.dialogDataFilter(row)
            this.dialogVisible = true;
        },
        //查看
        handleSelect(row) {
            this.title = "危险源详情"
            this.reqType = 'select'
            this.dialogDataFilter(row)
            this.dialogVisibleInfo = true;
        },
        dialogDataFilter(row) {
            console.log(row)
            this.formModel = row
            if (row.positions) {
                this.positionData.positionX = row.positions[0].x | 0
                this.positionData.positionY = row.positions[0].y | 0
                console.log(this.positionData, '默认坐标')
            }
            console.log(row.location)
            this.getPicList(row.deptId)
            setTimeout(() => {
                console.log(this.picList.some(item => item.projectPointPicId === row.location))
                const found = this.picList.some(item => item.projectPointPicId === row.location);
                if (found) {
                    this.picList.forEach(item => {
                        if (item.projectPointPicId === row.location) {
                            this.formModel.location = item.projectPointPicId
                            this.src = this.$store.state.config.inFilePrefix + item.picUrl
                        }
                    })
                } else {
                    this.src = ''
                }
                this.planPositionKey += 1
            }, 200);

        },
        projectInput(val) {
            console.log(val)
            this.getPicList(val)
            this.initUserList(val)

        },
        // 标注弹窗
        imageAnnotation(slot) {
            if (slot === 'slot') {
                if (!this.src) {
                    return this.$message.error('暂无标注')
                }
            } else {
                if (!this.src) {
                    return this.$message.error('请先选择一张图片')
                }
            }
            this.picKey += 1
            this.$set(this.pictrue, 'picUrl', this.src)
            this.markDialogVisible = true;
        },
        getPosition(val) {
            this.tempPosition = val
        },
        //选择平面图
        selectChange(id) {
            const selectedOption = this.picList.find(item => item.projectPointPicId === id);
            this.formModel.projectPointPicId = selectedOption.projectPointPicId
            this.src = this.$store.state.config.inFilePrefix + selectedOption.picUrl
        },
        //获取平面图列表
        getPicList(id) {
            getProjectPointPicList(
                {
                    picType: 1,
                    projectPointId: this.findNodeByName(this.deptOptions, id)
                }
            ).then(res => {
                this.picList = res.rows
                console.log(res, 'pic list')
            })
        },
        // 页面数据
        async getList() {
            const { code, rows, total } = await dangerousSourceList(this.searchMap)
            console.log(code, rows)
            if (code === 200) {
                this.loading = false
                this.dataList = rows
                this.total = total
            }
        },
        findNodeByName(tree, targetId) {
            for (let node of tree) {
                if (node.id === targetId) {
                    return node.projectPointId;
                }
                if (node.children && node.children.length > 0) {
                    const foundName = this.findNodeByName(node.children, targetId);
                    if (foundName) {
                        return foundName;
                    }
                }
            }
            return null;
        },
        /** 查询部门下拉树结构 */
        getDeptTree() {
            userDeptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },
        // 用户列表
        initUserList(id) {
            listUser({deptId:id}).then(res => {
                const resp = res
                this.userOptions = resp.rows
            })
        },
        selectCoordinate() {
            this.isVisibleMap = true;
            (this.mapForm = {
                mapSearch: undefined,
                maplnglat: undefined,
                mapaddress: undefined,
            }),
                this.initMap();
            // 初始化 Map 并在 Vue 组件的 mounted 钩子中设置它
        },
        // 地图初始化
        initMap() {
            this.mapKey += 1
            this.$nextTick(() => {
                // 创建一个矢量要素
                const iconFeature = new Feature({
                    geometry: new Point([118.1163, 24.4673]),
                });
                // 定义图片样式
                this.iconStyle = new Style({
                    image: new Icon({
                        anchor: [0.5, 1],
                        src: "https://openlayers.org/en/latest/examples/data/icon.png",
                    }),
                });
                // 设置要素样式
                iconFeature.setStyle(this.iconStyle);

                // 创建矢量数据源和图层
                this.vectorSource = new VectorSource({
                    features: [iconFeature],
                });
                const vectorLayer = new VectorLayer({
                    source: this.vectorSource,
                });
                this.map = new Map({
                    layers: [
                        new TileLayer({
                            source: new XYZ({
                                url: `http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.mapToken}`,
                            }),
                            // setStyle: "black",
                        }),
                        new TileLayer({
                            source: new XYZ({
                                url: `http://t0.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.mapToken}`,
                            }),
                            // setStyle: "black",
                        }),
                        vectorLayer,
                    ],
                    view: new View({
                        center: [116.92817687988281, 25.067563108389997],
                        zoom: 12,
                        projection: "EPSG:4326",
                    }),
                    // 使用 Vue 的 ref 来引用 DOM 元素
                    target: this.$refs.map,
                });
                this.map.addEventListener("click", this.MapClick);
            });
        },
        // 地图点击事件
        MapClick(e) {
            console.log(e)
            let coordinate = e.coordinate;
            console.log(coordinate);
            this.$set(this.formModel, "lng", coordinate[0])
            this.$set(this.formModel, "lat", coordinate[1])
            // this.getGeocoderAddress(coordinate[0], coordinate[1]).then((res) => {
            //     this.mapForm.mapaddress = res.result.formatted_address;
            // });
            // 创建一个新的图标要素
            this.mapForm.maplnglat = coordinate.join("/");
            let newIconFeature = new Feature({
                geometry: new Point(coordinate),
            });
            newIconFeature.setStyle(this.iconStyle);
            // 清除之前的图标要素
            this.vectorSource.clear();
            // 添加新的图标要素
            this.vectorSource.addFeature(newIconFeature);
        },
        // 根据地图坐标获取具体地址
        getGeocoderAddress(lon, lat) {
            return request({
                url: `/geocoder?postStr={'lon':${lon},'lat':${lat},'ver':1}&type=geocode&tk=${this.mapToken}`,
                method: "post",
                type: "map",
            });
        },
        closeMap() {
            this.map.getLayers().forEach(layer => {
                if (layer instanceof TileLayer) {
                    this.map.removeLayer(layer);
                }
            });
        },
        // 根据地址获取对应的地图坐标
        getGeocoderLonLat(keyWord) {
            return request({
                url: `/geocoder?ds={'keyWord':"${keyWord}"}&tk=${this.mapToken}`,
                method: "post",
                type: "map",
            });
        },
        // 地图确定按钮
        mapSubmitForm() {
            // let tempLonLatArr = this.mapForm.maplnglat;
            this.isVisibleMap = false;
        },
    },
    mounted() {
        this.getList()
        this.getDeptTree()
    },
}
</script>
<style lang="less">
.control {
    .el-table__cell {
        .cell {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
}
</style>
<style lang="less" scoped>
@dialog-height: 860px;

.list_container {
    flex-direction: column;
    background: url("@/assets/images/home/content.png") no-repeat;
    background-size: cover;

    .content_container {
        padding: 15px 20px;
        overflow-y: scroll;
    }

    .table_container {
        margin-bottom: 25px;
    }

    .pagination_container {
        display: flex;
        justify-content: space-between;
        height: 32px;
    }
}

.basiceinformation-container {
    height: calc(@dialog-height - 230px);
    overflow: auto;

    .project-body {
        padding: 0 15px;
        height: 100%;
    }
}

// 天地图样式？
/deep/ .ol-zoom.ol-unselectable.ol-control {
    display: none;
}

/deep/ .ol-rotate.ol-unselectable.ol-control.ol-hidden {
    display: none;
}

/deep/ .map-Contern {
    .map-form {
        padding: 24px;

        .el-form-item--small.el-form-item {
            margin-bottom: 12px;
        }
    }

    .map-footer-btn {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-bottom: 10px;
    }
}

/deep/ .map-Contern {
    position: absolute;
    top: 0;
    right: 0;
    background: rgba(19, 21, 26, 0.6);
}
</style>
